package game.server;

import java.io.IOException;
import java.net.UnknownHostException;

import game.server.net.TestGameConnectHandler;
import game.server.world.GameWorld;
import game.server.world.rtree.RTreeWorld;

import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;

import rtree.RTreeException;

public class ServerBoot {
	
	/* ---------------- PARAM SYNTAX ---------------- */
	public static final String PARAM_PORT = "-p";
	
	/* --------------- DEFAULT VALUES --------------- */
	public static final int DEFAULT_PORT = 5353;
	
	/* --------------- PARAMETRIZABLE --------------- */
	private int port;
	
	/* ------------------ UTILITY ------------------- */
	// private Logger log = Logger.getLogger(getClass());
	
	/* -------------- SERVER COMPONENTS ------------- */
	private IServer netServer;
	private GameWorld world;
	
	/* -------------------- IMPL -------------------- */
	public ServerBoot() {
		port = DEFAULT_PORT;
	}
	
	public void loadWorld(){
		try {
			this.world = new RTreeWorld();
		} catch (RTreeException e) {
			e.printStackTrace();
		}
	}
	
	public void startNetwork(){
		try {
			this.netServer = new Server(port, new TestGameConnectHandler(this.world));
			this.netServer.start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public void startWorld(){
		while (true){
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			world.update();
		}
	}

	
	public void readArgs(String[] args){
		int offset = 0; 
		
		while (offset < args.length){
			if (args[offset].equals(PARAM_PORT)){
				port = Integer.parseInt(args[offset + 1]);
				offset += 2;
			} else {
				System.out.println("unkown arg '" + args[offset] + "'");
				++offset;
			}
		}
	}
	
	public static void main(String[] args) {
		ServerBoot boot = new ServerBoot();
		boot.readArgs(args);
		
		boot.loadWorld();
		boot.startNetwork();
		boot.startWorld();
	}
}
